var resUrl;
var freeNum = 0;
var forNum = 0;
var countNum = 0;
var timeNum = 0;
var num = 0;
var freeMap = new HashMap();
var forMap = new HashMap();
var serMap = new HashMap();
$(function () {
    //********************************************************图片上传************************************************************//
    $("#imgThumb").change(function (e) {
        var objUrl = getObjectURL(this.files[0]);
        var file=e.target.files[0],src=window.createObjectURL&&window.createObjectURL(file)||window.URL&&window.URL.createObjectURL(file)||window.webkitURL && window.webkitURL.createObjectURL(file);
        showLoading();
        uploadFileToOssSync("imgThumb",false ,uploadImgSuccess,uploadFailed);
    });
    //*********************************************************试听文件上传********************************************************************
    var type =  $("#hiddenType").val();
    if(type == 'lesson_audio'){
        //音频文件
        $("#free").attr("accept","audio/wav,audio/mp3");
    }
    if(type == 'lesson_video'){
        //视频文件
        $("#free").attr("accept","video/mp4,audio/ogg,video/WebM");
        //video/avi,
    }
    if(type == 'lesson_image'){
        //图文文件
        $("#free").attr("accept","text/html");
    }
    $("#free").change(function (e) {
            freeNum++;
            var objUrl = getObjectURL(this.files[0]);
        var file=e.target.files[0],src=window.createObjectURL&&window.createObjectURL(file)||window.URL&&window.URL.createObjectURL(file)||window.webkitURL && window.webkitURL.createObjectURL(file);
            $("#audio").attr("src", objUrl);
            var index = file.name.lastIndexOf(".");
            var realName = file.name.substr(0, index);
            var size = getFileSize("free");
            if ($("#hiddenType").val() != 'lesson_image') {
                getFreeTime(size, realName);
            }
        });

    //**********************************************************************正式文件上传************************************************************//
    var type =  $("#hiddenType").val();
    if(type == 'lesson_audio'){
        //音频文件
        $("#formal").attr("accept","audio/wav,audio/mp3");
    }
    if(type == 'lesson_video'){
        //视频文件
        $("#formal").attr("accept","video/mp4,audio/ogg,video/WebM");
        //video/avi,
    }
    if(type == 'lesson_image'){
        //视频文件
        $("#formal").attr("accept","text/html");
    }
    $("#formal").change(function (e) {
        var files = e.target.files;
        for(var i = 0 ;i <= files.length - 1 ; i++) {
        //forNum++;
        var objUrl = getObjectURL(this.files[i]);
        var file=e.target.files[i],src=window.createObjectURL&&window.createObjectURL(file)||window.URL&&window.URL.createObjectURL(file)||window.webkitURL && window.webkitURL.createObjectURL(file);
        var div = '<audio id="formalAudio'+ timeNum +'" controls="" style="display:none;"></audio>';
        $("#formalAudioDiv").append(div);
        $("#formalAudio"+ timeNum).attr("src", objUrl);
        var index = file.name.lastIndexOf(".");
        var realName = file.name.substr(0,index);
        if(type == 'lesson_image') {
            forMap.put(forNum, '{"fileName":"' + realName + '",');
            var div = '<div style="padding-left: 160px" id="forLesson'+forNum+'"><input id="musicName' + forNum + '" value="' + realName + '" style="width: 180px;margin-right:60px" ><input type="hidden" id="forlessCode' + forNum + '" name="lessonCode" value="" ><span style="color: red">*</span>排序 <input id="sortNum' + forNum + '" name="sortNum' + forNum + '" required style="width: 50px" ' +
                'onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}"> ' +
                '<button  style="margin-left:60px" class="btn btn-primary btn-outline" type="button" onclick="clearFor('+ forNum +')">删除</button></div>';//定义DIV的样式
            $("#forMusDiv").append(div);
            forNum++;
        }
            var fileSize = files[i].size;
            fileSize = fileSize / 1024;//kb
            fileSize = fileSize / 1024;//mb
            fileSize = fileSize.toFixed(1);
            if(type != 'lesson_image'){
            getFormalTime(fileSize, realName,timeNum);
         }
            showLoading();
            uploadFileToOssSync("formal",false,uploadFormalSuccess,uploadFailed);
        }
    });




//*******************************************************初始化操作**********************************************************
        initTextSearch("#pIsvName"
            ,basePath + 'health/searchIsvList?t='+ (new Date()).getTime()+'&isvName='
            ,['isvPid','isvName'],{'isvPid':"服务商pid",'isvName':'服务商名称'}
            ,'isvPid','isvName'
            ,true,
            selectPisvValue,
            noSelectPisvValue,
            false
        );
        initTextSearch("#pDocName"
            ,basePath + 'health/searchDocList?t='+ (new Date()).getTime()+'&docName='
            ,['docCode','docName'],{'docCode':"专家编码",'docName':'专家姓名'}
            ,'docName','docName'
            ,true,
            selectPdocValue,
            noSelectPdocValue,
            false
        );

    laydate.render({
        elem: '#topTime'
        ,type: 'datetime'
        ,range: true //或 range: '~' 来自定义分割字符
        // ,value: dateFtt("yyyy-MM-dd hh:mm:ss", preDate) + ' - ' + dateFtt("yyyy-MM-dd hh:mm:ss", curDate)
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
    laydate.render({
        elem: '#freeTime'
        ,type: 'datetime'
        ,range: true //或 range: '~' 来自定义分割字符
       // ,value: dateFtt("yyyy-MM-dd hh:mm:ss", freeStarttime) + ' - ' + dateFtt("yyyy-MM-dd hh:mm:ss", freeEndtime)
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
    if($("#isTop").val() == 'N'){
        $("#topDiv").hide();
        $("#topTime").attr("required","false");
    }

    if($("#sample").val() == 'N'){
        $("#freeDiv").hide();
        $("#freeDiv").attr("required","false");
    }

    if($("#isHaveFreeTime").val() == 'N'){
        $("#freeTimeDiv").hide();
        $("#freeTime").attr("required","false");
    }else{
        $("#freeTime").attr("required","true");
    }


    if($("#isFree").val() == 'N'){
        $("#price").attr("required","true");
        $("#price").attr("readOnly",false);
    }else{
        $("#price").val('0');
        $("#price").attr("required","false");
        $("#price").attr("readOnly","true");
    }


    //初始化课程列表
    if(contentDto && contentDto.contentType == 'lesson_image'){
        //initFreeImageData();
        initForImageData();
    }else {
        if ($("#hiddenId").val() && contentDto && contentDto.freeLesson) {
            initFreeLessonData();
            initForLessonData();
            initSeriesLessonData();
        }
    }

    var id = $("#hiddenId").val();

    if( id == '' || id == null){
        var data = getFromData('#contentForm');
        contentDto.bizCode = data.bizCode;
        contentDto.showType = data.showType;
        contentDto.contentType = data.contentType;
        contentDto.detailContent = '<p style="color:#c8ced4;">富文本 (包含课程大纲，课程说明，课程特点，适用人群）</p>';
        contentDto.isFree = data.isFree;
        contentDto.isHaveFreeTime = data.isHaveFreeTime;
        contentDto.isPlatformCharge = data.isPlatformCharge;
        contentDto.isTop = data.isTop;
        contentDto.hasMidPage = data.hasMidPage;
        contentDto.sample = data.sample;
    }
});

function uploadFree() {
    showLoading();
    uploadFileToOssSync("free",false,uploadFreeSuccess,uploadFailed);
}

function initFreeLessonData() {
    var div = '';
    for (var i = 0; i < contentDto.freeLesson.length; i++) {
        var thisLesson = contentDto.freeLesson[i];
        div += '<div style="padding-left: 160px" id="freeLesson'+freeNum+'"><input id="freeMusicName' + freeNum + '" value="' + thisLesson.fileName + '" style="width: 180px;margin-right:60px" ><input id="freeMusicSize' + freeNum + '" value="'+ thisLesson.fileSize + 'M" style="width: 60px;margin-right:30px" readonly><input type="hidden" id="lessonCode'+freeNum+'" name="lessonCode" value="'+thisLesson.lessonCode+'" > <span style="color: red">*</span>时长：<input id="min" '+ freeNum + ' value="' + Math.floor(thisLesson.duration/60) +'" style="width: 50px" readonly="readonly" >分<input id="sec"' + freeNum + ' value="' + Math.floor(thisLesson.duration%60) + '" style="width: 50px" readonly="readonly" >秒 <button class="btn btn-primary btn-outline" type="button" style="margin-left:60px" onclick="clearFree('+freeNum+')">删除</button></div>';//定义DIV的样式
        freeMap.put(freeNum,'{"fileName":"'+thisLesson.fileName+'","fileSize":"'+thisLesson.fileSize+'","duration":"'+thisLesson.duration+'","lessonUrl":"'+thisLesson.lessonUrl+'"}');
        freeNum++;
    }
    $("#musDiv").append(div);
}

function initForLessonData() {
    var div = '';
    for (var i = 0; i < contentDto.formalLesson.length; i++) {
        var thisLesson = contentDto.formalLesson[i];
        div += '<div style="padding-left: 160px" id="forLesson'+forNum+'"><input id="musicName' + forNum + '" value="' + thisLesson.fileName + '" style="width: 180px;margin-right:60px" ><input id="forMusicSize' + forNum +'" value="'+ thisLesson.fileSize + 'M" style="width: 60px;margin-right:30px" readonly><input type="hidden" id="forlessCode' + forNum + '" name="lessonCode" value="'+thisLesson.lessonCode+'" ><span style="color: red">*</span>排序 <input id="sortNum' + forNum + '" name="sortNum" value="'+thisLesson.sortNum+'" style="width: 50px" ' +
            'onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}" required> <span style="color: red">*</span>时长：<input id="min" '+ forNum + ' value="' + Math.floor(thisLesson.duration/60) +'" style="width: 50px" readonly="readonly" >分<input id="sec"' + forNum + ' value="' + Math.floor(thisLesson.duration%60) + '" style="width: 50px" readonly="readonly" >秒 ' +
            '<button class="btn btn-primary btn-outline"  style="margin-left:60px" type="button" onclick="clearFor('+ forNum +')">删除</button></div>';//定义DIV的样式
        forMap.put(forNum,'{"fileName":"'+thisLesson.fileName+'","fileSize":"'+thisLesson.fileSize+'","duration":"'+thisLesson.duration+'","lessonUrl":"'+thisLesson.lessonUrl+'"}');
        forNum++;
        countNum ++;
    }
    $("#forMusDiv").append(div);
}

function initSeriesLessonData(){
    var div = '';
    for (var i = 0; i < contentDto.lesson.length; i++) {
        var thisLesson = contentDto.lesson[i];
        div += '<div name="Lesson" id="Lesson'+num+'"><input id="lessRef'+num+'" name="hiddenRefCode" type="hidden" value="'+thisLesson.refCode+'"><input type="hidden" id="lessonCode' + num + '" name="lessonCode" value="'+thisLesson.lessonCode+'" ><input id="musicName" style="width: 180px;margin-right:60px" readonly="readonly" value= "'+ thisLesson.seriesName + '"><span style="color: red">*</span>排序 <input id="sortNum'+num+'" name="sortNum" style="width: 50px" required value="'+thisLesson.sortNum+'" ' +
            'onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}"> <button class="btn btn-primary btn-outline" style="margin-left:60px"  type="button" onclick="clearLesson('+num+')">删除</button></div>';//定义DIV的样式
        serMap.put(num,'{"fileName":"'+thisLesson.title+'","sortNum":"'+thisLesson.sortNum+'","contentCode":"'+thisLesson.refCode+'"}');
        num++;
    }
    $("#assCommon").append(div);
}


function initForImageData() {
    var div ="";
    for (var i = 0; i < contentDto.formalLesson.length; i++) {
        var thisLesson = contentDto.formalLesson[i];
        div += '<div style="padding-left: 160px" id="forLesson' + forNum + '"><input id="musicName' + forNum + '" value="' + thisLesson.fileName + '" style="width: 180px;margin-right:60px" ><input type="hidden" id="forlessCode' + forNum + '" name="lessonCode" value="'+thisLesson.lessonCode+'" ><span style="color: red">*</span>排序 <input id="sortNum' + forNum + '" name="sortNum' + forNum + '" value="' + thisLesson.sortNum + '" style="width: 50px" ' +
            'onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}"> <button class="btn btn-primary btn-outline" style="margin-left:60px" type="button" onclick="clearFor(' + forNum + ')">删除</button></div>';//定义DIV的样式
        forMap.put(forNum,'{"fileName":"'+thisLesson.fileName+'","lessonUrl":"'+thisLesson.lessonUrl+'"}');
        forNum++;
        countNum ++;
    }
    $("#forMusDiv").append(div);
}


//*******************************************************获得文件时长/大小**********************************************************
<!--获取mp3文件的时间 兼容浏览器-->
function getFreeTime(size ,fileName) {
    setTimeout(function () {
        var duration = $("#audio")[0].duration;
        if(isNaN(duration)){
            getFreeTime(size ,fileName);
        } else{
            freeMap.put(freeNum,'{"fileName":"'+fileName+'","fileSize":"'+size+'","duration":"'+duration);
            if(freeMap.size() >= 2){
                toastr.error("只能上传一个试听课程");
                freeMap.remove(freeNum);
                return;
            }
            var div = '<div style="padding-left: 160px" id="freeLesson'+freeNum+'"><input id="freeMusicName' + freeNum + '" value="' + fileName + '" style="width: 180px;margin-right:60px" ><input id="freeMusicSize' + freeNum +'" value="'+ size + 'M" style="width: 60px;margin-right:30px" readonly><input type="hidden" id="lessonCode' + freeNum + '" name="lessonCode" value="" ><span style="color: red">*</span>时长：<input id="min" '+ freeNum + ' value="' + Math.floor($("#audio")[0].duration/60) +'" style="width: 50px" readonly="readonly" >分<input id="sec"' + freeNum + ' value="' + Math.floor($("#audio")[0].duration%60) + '" style="width: 50px" readonly="readonly" >秒 <button class="btn btn-primary btn-outline" style="margin-left:60px" type="button" onclick="clearFree('+freeNum+')">删除</button></div>';//定义DIV的样式
            $("#musDiv").append(div);
            uploadFree();
        }
    }, 10);
}

function getFormalTime(size ,fileName,audioNum) {
    setTimeout(function () {
        var duration = $("#formalAudio"+ audioNum )[0].duration;
        if(isNaN(duration)){
            getFormalTime(size ,fileName,audioNum);
        } else{
            var div = '<div style="padding-left: 160px" id="forLesson'+forNum+'"><input id="musicName' + forNum + '" value="' + fileName + '" style="width: 180px;margin-right:60px" ><input id="forMusicSize' + forNum +'" value="'+ size + 'M" style="width: 60px;margin-right:30px" readonly><input type="hidden" id="lessonCode' + forNum + '" name="lessonCode" value="" ><span style="color: red">*</span>排序 <input id="sortNum' + forNum + '" name="sortNum'+ forNum +'" style="width: 50px" ' +
                'onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}" required> <span style="color: red">*</span>时长：<input id="min'+ forNum + '" value="' + Math.floor(duration/60) +'" style="width: 50px" readonly="readonly" >分<input id="sec' + forNum + '" value="' + Math.floor(duration%60) + '" style="width: 50px" readonly="readonly" >秒 <button class="btn btn-primary btn-outline" style="margin-left:60px" type="button" onclick="clearFor('+ forNum +')">删除</button></div>';//定义DIV的样式
            $("#forMusDiv").append(div);
            forMap.put(forNum,'{"fileName":"'+fileName+'","fileSize":"'+size+'","duration":"'+ duration);
            forNum++;
        }
    }, 10);
    timeNum ++;
}
<!--把文件转换成可读URL-->
function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

function getFileSize(eleId) {
    try {
        var size = 0;
        size = $('#' + eleId)[0].files[0].size;//byte
        size = size / 1024;//kb
        size = size / 1024;//mb
        size = size.toFixed(1);
        return size;
    } catch (e) {
        toastr.error("错误：" + e);
        return -1;
    }
}


//*******************************************************加载科室信息**********************************************************
function loadTwoData(value, selectValue){
    $.ajax({
        type: 'post',
        url: basePath + 'health/loadDeptTwo?deptOne='+value,
        dataType: 'json',
        contentType: "application/json",
        success : function (data) {
            if(data.result== true){
                    $("#deptNameTwo").val('');
                    var htmlStr = '<option value="">--请选择--</option>';
                    if (data.content) {
                        for (var i=0; i<data.content.length; i++) {
                            htmlStr += '<option value="'+data.content[i].deptCode+'">'+data.content[i].deptName+'</option>';
                        }
                    }
                    $("#deptNameTwo").html(htmlStr);
                    if(selectValue){
                        $("#deptNameTwo").val(selectValue);
                    }
            }else{
                toastr.error("加载数据失败");
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}
function addLoadTwoData(value){
    $("#deptSecName").val('');
    doSickRefresh();
    $.ajax({
        type: 'post',
        url: basePath + 'health/loadDeptTwo?deptOne='+value,
        dataType: 'json',
        contentType: "application/json",
        success : function (data) {
            if(data.result== true){
                $("#deptSecName").val('');
                var htmlStr = '<option value="">--请选择--</option>';
                if (data.content) {
                    for (var i=0; i<data.content.length; i++) {
                        htmlStr += '<option value="'+data.content[i].deptCode+'">'+data.content[i].deptName+'</option>';
                    }
                }
                $("#deptSecName").html(htmlStr);
            }else{
                toastr.error("加载数据失败");
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function selectPisvValue(data){
    if (!data || !data.isvPid) {
        return;
    }
    $('#PisvPid').val(data.isvPid);
}
function noSelectPisvValue(){
    $('#PisvPid').val("");
}
function selectPdocValue(data){
    if (!data || !data.docCode) {
        return;
    }
    $('#pDocCode').val(data.docCode);
    $.ajax({
        type: 'post',
        url: basePath + 'health/loadDocDept?docCode='+data.docCode,
        dataType: 'json',
        contentType: "application/json",
        success : function (r) {
            if(r.result== true){
                $("#deptNameOne").val(r.content.pDeptCode);
                loadTwoData(r.content.pDeptCode,r.content.cDeptCode);
            }else{
                toastr.error("加载数据失败");
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function noSelectPdocValue(){
    $('#pDocCode').val("");
}

function selectSick(){
    $("#sick").val("");
    $("#deptFirName").val("");
    $("#deptSecName").val("");
    doSickRefresh();
    $("#selectSick").modal(true);
}

function cancelSick(){
    $("#deptFirName").val("");
    $("#deptSecName").val("");
    $("#sick").val("");
    $("#selectSick").modal('hide');
}

function doSickRefresh() {
    var sick = $("#sick").val();
    var deptFirName = $("#deptFirName").val();
    var deptSecName = $("#deptSecName").val();
    if(sick == null){
        sick = '';
    }
    if(deptFirName == null){
        deptFirName = '';
    }
    if(deptSecName == null){
        deptSecName = '';
    }
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'health/getGridDataForCheckbox?sicknessName='+sick+'&oneLevelDeptCode='+deptFirName+'&twoLevelDeptCode='+deptSecName+'&t='+new Date().getTime(),
    });
}

function addDept(){
    $("#deptName").val('');
    doDeptRefresh();
    $("#selectDept").modal(true);
}

function doDeptRefresh(){
    var deptName = $.trim($("#deptName").val());
    $('#dataDeptTable').bootstrapTable('refresh', {
        url: basePath + 'health/findDeptList?deptName='+deptName+'&t='+new Date().getTime(),
    });
}

function clickDept() {
    var deptList=[];
    var depts=getSelectedRows('#dataDeptTable');
    for (var cell in depts){
        deptList.push({value:depts[cell].deptCode,text:depts[cell].deptName});
    }
    $('#selectDept').modal('hide');
    addLableByList(deptList,"deptOne");
}

function getParams(params) {
    var sickListStr  = getlableNote('sicknessName',false).join(",");
    var titleListStr  = getlableNote('serTitle',false).join(",");
    var deptListStr = getlableNote('deptOne',false).join(",");
    if(sickListStr == ','){
        sickListStr = '';
    }
    if(titleListStr == ','){
        titleListStr = '';
    }
    if(deptListStr == ','){
        deptListStr = '';
    }
    var postData = {
        sicknessListStr : sickListStr,
        titleListStr : titleListStr,
        deptListStr : deptListStr,
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
    return postData;
}


$('#dataTable').on("click-row.bs.table", function (e, row, $element) {
    // checkBox 的勾选
    var index = $element[0].rowIndex - 1;
    $('#dataTable').bootstrapTable('uncheckAll');
    $('#dataTable').bootstrapTable('check', index);
});

function doRefresh() {
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'health/healthContentPage?t='+new Date().getTime()
    });
}

function clickSick() {
    var sickList=[];
    var sicks=getSelectedRows('#dataTable');
    for (var cell in sicks){
        sickList.push({value:sicks[cell].refCode,text:sicks[cell].sicknessName});
    }
    $('#selectSick').modal('hide');
    addLableByList(sickList,"sicknessName");
}


//*************************************************************关联课程*****************************************************************

function selectLesson(){
    $("#lesson").val("");
    $("#lessonType").val("");
    doSerRefresh();
    $("#selectLesson").modal(true);
}

function doSerRefresh() {
    var list = [];
    var forArr = serMap.keySet();
    var idStr = "";
    if (forArr != null) {
        for (var i = 0; i < forArr.length; i++) {
            list.push($("#lessRef" + forArr[i]).val());
        }
        if (list.length > 0) {
            idStr = list.join(",");
        }
        console.log(idStr);
    }
    var lessonName = $("#lesson").val();
    var contentType = $("#lessonType").val();
    $('#dataLessonTable').bootstrapTable('refresh', {
        url: basePath + 'health/getCommonDataForCheckbox?idListStr='+idStr+'&lessonName='+lessonName+'&contentType='+contentType+'&t='+new Date().getTime()
    });
}

$('#dataLessonTable').on("click-row.bs.table", function (e, row, $element) {
    // checkBox 的勾选
    var index = $element[0].rowIndex - 1;
    $('#dataLessonTable').bootstrapTable('uncheckAll');
    $('#dataLessonTable').bootstrapTable('check', index);
});

function clickLesson() {
    var sicks=getSelectedRows('#dataLessonTable');
    var sickList =[];
    var div = '';
    for (var cell in sicks){
         div += '<div name="LessonDiv" id="Lesson' + num + '"><input id="lessRef' + num + '" name="hiddenRefCode" type="hidden" value="' + sicks[cell].contentCode + '"><input id="musicName' + num + '" style="width: 180px;margin-right:60px" readonly="readonly" value= "' + sicks[cell].title + '"><span style="color: red">*</span>排序 <input id="sortNum'+num+'" name="sortNum" style="width: 50px"  required value="' + sicks[cell].sortNum + '" ' +
             'onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,\'\')}else{this.value=this.value.replace(/\\D/g,\'\')}"> <button class="btn btn-primary btn-outline" style="margin-left:60px" type="button" onclick="clearLesson(' + num + ')">删除</button></div>';//定义DIV的样式
        serMap.put(num,'{"fileName":"'+sicks[cell].title+'","sortNum":"'+sicks[cell].sortNum+'","contentCode":"'+sicks[cell].contentCode+'"}');
        sickList.push({value:sicks[cell].refCode,text:sicks[cell].title});
        num++;
    }
    $("#assCommon").append(div);
    $('#selectLesson').modal('hide');
}

//**********************************************************************************************************************

function changeFree(value){
    if(value == 'N'){
        $("#freeDiv").hide();
        $("#free").val('');
        var div = document.getElementById("musDiv");
        while (div.hasChildNodes()){ //当div下还存在子节点时 循环继续
            div.removeChild(div.firstChild);
        }
        freeMap = new HashMap();
    }else{
        $("#freeDiv").show();
    }
}

function changeIsFree(value) {
    if(value == 'N'){
        $("#price").val('');
        $("#price").attr("required","true");
        $("#price").attr("readOnly",false);
    }else{
        $("#price").val('0');
        $("#price").attr("required","false");
        $("#price").attr("readOnly","true");
    }
}

function changeTop(value){
    if(value == 'N'){
        $("#topDiv").hide();
        $("#topTime").val('');
        $("#topTime").attr("required","false");
    }else{
        $("#topDiv").show();
        $("#topTime").attr("required","true");
    }
}


function changeFreeTime(value){
    if(value == 'N'){
        $("#freeTimeDiv").hide();
        $("#freeTime").val('');
        $("#freeTime").attr("required","false");
    }else{
        $("#freeTimeDiv").show();
        $("#freeTime").attr("required","true");
    }
}

function doCheckImage() {
    if($("#hiddenType").val() != 'lesson_series') {
        var idListStr = getlableNote('sicknessName', false).join(",");
        if (idListStr == '' || idListStr == null) {
            toastr.error("请添加对应疾病!");
            return;
        }
    }
    if(!$("#contentForm").valid()) return;//校验不通过

    if(!checkForm()){
        return;
    }
    fileCheck("imgThumb", "thumb", 40*1024, 64, 64,
        "您上传的图片大小超出限制范围（40k以内），无法上传，请重新上传符合要求的图片！",
        "您上传的图片尺寸不符合要求（64*64px），可能会影响APP展示效果，是否继续保存？",doSave);
}

function checkForm(){
    var hiddenType = $("#hiddenType").val();
    var sample = $("#sample").val();
    if(hiddenType != 'lesson_series') {
        if (sample == 'Y' && (freeMap.size() == 0 && hiddenType == 'lesson_audio')) {
            toastr.error("请上传试听课程!");
            return false;
        }
        if (sample == 'Y' && (freeMap.size() == 0 && hiddenType == 'lesson_video')) {
            toastr.error("请上传试看课程!");
            return false;
        }
        if(sample == 'Y' && freeMap.size() > 0){
            var freeArr = freeMap.keySet();
            for (var i = 0; i < freeArr.length; i++) {
                var freeName = $("#freeMusicName"+freeArr[i]).val();
                if($.trim(freeName) == null || $.trim(freeName) == ''){
                    toastr.error("课程名不能为空!");
                    return false;
                }
            }
        }
        if (forMap.size() == 0) {
            toastr.error("请上传正式课程!");
            return false;
        }
        var forArr = forMap.keySet();
        for (var i = 0; i < forArr.length; i++) {
            if(hiddenType != 'lesson_image') {
                var forName = $("#musicName" + forArr[i]).val();
                if ($.trim(forName) == null || $.trim(forName) == '') {
                    toastr.error("课程名不能为空!");
                    return false;
                }
            }
        }
        var nameArr = [];
        if(forMap.size() > 0) {
            var forArr = forMap.keySet();
            for (var i = 0; i < forArr.length; i++) {
                var forName = $("#musicName"+forArr[i]).val();
                nameArr.push(forName);
            }
        }
        var nary=nameArr.sort();
        for(var i=0;i<nameArr.length;i++) {
            if (nary[i] == nary[i + 1]) {
                toastr.error('课程名不能相同');
                return false;
            }
        }
    }else {
        if (serMap.size() == 0) {
            toastr.error("请添加关联课程!");
            return false;
        }
    }
        if (($("#originPrice").val() != '') && (Number($("#originPrice").val()) < Number($("#price").val()))) {
            toastr.error("原价必须大于或等于现价!");
            return false;
        }
        var detailContent = $.trim(ue.getContent());
        if (($("#detailLinkUrl").val() == null || $("#detailLinkUrl").val() == '') && (detailContent == null || detailContent == '' || detailContent == '<p style="color:#c8ced4;">富文本 (包含课程大纲，课程说明，课程特点，适用人群）</p>')) {
            toastr.error("详情为必填项");
            return false;
        }
        if ($("#hiddenId").val() == null || $("#hiddenId").val() == '') {
            imgSrcDefault;
            var img = $('#thumb').attr('src');
            if ((!img || img == '' || img == imgSrcDefault)) {
                toastr.error('列表小图不能为空');
                return false;
            }
        }
        return true;
    }

function doSave(){
    var contentCode = $("#hiddenContent").val();
    var contentType = $("#hiddenType").val();
    var bizCode = $("#hiddenCode").val();
    var sample = $("#sample").val();
    var additionalRemarks = $("#additionalRemarks").val();
    var data = getFromData('#contentForm');
    var originReadedTotal = (!data.originReadedTotal || data.originReadedTotal == '') ? 0 : data.originReadedTotal;
    var originLikedTotal = (!data.originLikedTotal || data.originLikedTotal == '') ? 0 : data.originLikedTotal;
    var originBuyTotal = (!data.originBuyTotal || data.originBuyTotal == '') ? 0 : data.originBuyTotal;
    var detailContent = $.trim(ue.getContent());
    if(detailContent == '<p style="color:#c8ced4;">富文本 (包含课程大纲，课程说明，课程特点，适用人群）</p>'){
        detailContent = '';
    }
    var idListStr = getlableNote('sicknessName', false).join(",");
    var deptListStr = getlableNote('deptOne',false).join(",");
    var summary = $("#summary").val();
    var tips = $("#tips").val();
    var topStarttimeStr = '';
    var topEndtimeStr = '';
    var timeInterval = $("#topTime").val();
    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            topStarttimeStr = dates[0];
            topEndtimeStr = dates[1];
        }
    }
    if($("#isTop").val() == 'Y' && judgementDate(topStarttimeStr,topEndtimeStr) <= 0){
        toastr.error('置顶开始时间必须小于置顶结束时间 ');
        return;
    }
    var freeStarttimeStr = '';
    var freeEndtimeStr = '';
    timeInterval = $("#freeTime").val();
    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            freeStarttimeStr = dates[0];
            freeEndtimeStr = dates[1];
        }
    }
    if($("#isHaveFreeTime").val() == 'Y' && judgementDate(freeStarttimeStr,freeEndtimeStr) <= 0){
        toastr.error('免费开始时间必须小于免费结束时间 ');
        return;
    }
    var titleListStr  =  getlableNote('serTitle',false).join(",");
    var sicknessName = $.trim($("#sicknessName").val());
    var detailLinkUrl = $("#detailLinkUrl").val();
    var sortNum = (!data.sortNum || data.sortNum == '') ? 999 : data.sortNum;
    var freeLessons = [];
    var forLessons = [];
    if(contentType != 'lesson_series'){
        if(sample == 'Y'){
            var freeArr = freeMap.keySet();
            for (var i = 0; i < freeArr.length; i++) {
                var freeLesson = {};
                var obj = JSON.parse(freeMap.get(freeArr[i]));
                if(contentType != 'lesson_image'){
                    freeLesson.fileSize = obj.fileSize;
                    freeLesson.duration = obj.duration;
                }
                var freeName = $("#freeMusicName"+freeArr[i]).val();
                freeLesson.fileName = freeName;
                freeLesson.lessonUrl = obj.lessonUrl;
                freeLesson.lessonCode = $("#lessonCode"+freeArr[i]).val();
                freeLessons.push(freeLesson);
            }
        }
        var forArr = forMap.keySet();
        for (var i = 0; i < forArr.length; i++) {
            var forLesson = {};
            var obj = JSON.parse(forMap.get(forArr[i]));
            if(contentType != 'lesson_image') {
                forLesson.fileSize = obj.fileSize;
                forLesson.duration = obj.duration;
            }
            var forName = $("#musicName"+forArr[i]).val();
            forLesson.fileName = forName;
            forLesson.lessonUrl = obj.lessonUrl;
            forLesson.sortNum = $("#sortNum"+forArr[i]).val();
            forLesson.lessonCode = $("#forlessCode"+forArr[i]).val();
            forLessons.push(forLesson);
        }
    }else{
        //说明是系列课程
        var lesson = [];
        var forArr = serMap.keySet();
        for (var i = 0; i < forArr.length; i++) {
            var forLesson = {};
            var obj = JSON.parse(serMap.get(forArr[i]));
            forLesson.title = obj.fileName;
            forLesson.sortNum = $("#sortNum"+forArr[i]).val();
            forLesson.contentCode = obj.contentCode;
            lesson.push(forLesson);
        }
    }
    var postData = {
        id : data.id,
        bizCode : bizCode,
        showType : data.showType,
        contentCode : contentCode,
        contentType : contentType,
        topStarttime : topStarttimeStr,
        topEndtime : topEndtimeStr,
        isvPid : data.isvPid,
        hasMidPage : data.hasMidPage,
        isTop : data.isTop,
        title : data.title,
        summary : summary,
        sortNum : sortNum,
        tips : tips,
        thumb : resUrl,
        sample : sample,
        duration : data.duration,
        docCode : data.docCode,
        oneLevelDeptCode : data.oneLevelDeptCode,
        twoLevelDeptCode : data.twoLevelDeptCode,
        sicknessName : sicknessName,
        isFree : data.isFree,
        isPlatformCharge : data.isPlatformCharge,
        originPrice : data.originPrice,
        price : data.price,
        additionalRemarks : additionalRemarks,
        isHaveFreeTime : data.isHaveFreeTime,
        freeStarttime : freeStarttimeStr,
        freeEndtime : freeEndtimeStr,
        originReadedTotal : originReadedTotal,
        originLikedTotal : originLikedTotal,
        originBuyTotal : originBuyTotal,
        detailContent : detailContent,
        detailLinkUrl : detailLinkUrl,
        idListStr: idListStr,
        freeLesson : freeLessons,
        formalLesson : forLessons,
        lesson : lesson,
        titleListStr : titleListStr,
        deptListStr : deptListStr
    };
    var url = basePath + 'health/addContent';
    if(editType == 'edit') {
        url = basePath + 'health/editContent';
    }
    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        contentType : "application/json; charset=UTF-8",
        data: JSON.stringify(postData),
        beforeSend:function () {
            showLoading();
        }, complete:function(){
            hideLoading();
        }, success : function (data) {
            if(data.result){
                doBack();
            }else{
                toastr.error(data.message);
            }
        }, error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

//*****************************************点击删除按钮**********************************************

function clearLesson(value){
    $("#Lesson"+value).remove();
    serMap.remove(value);
}

function clearFree(value){
    $("#freeLesson"+value).remove();
    freeMap.remove(value);
    $("#free").val('');
}

function clearFor(value){
    $("#forLesson"+value).remove();
    forMap.remove(value);
    $("#formal").val('');
}

function delAllLesson(){
    var str = '删除后无法复原，你确定全部删除吗?';
    swalToastr('操作提示', str, 'warning',doDelAllLesson , '确定');
}

function doDelAllLesson() {
    var div = document.getElementById("assCommon");
    while (div.hasChildNodes()){  //当div下还存在子节点时 循环继续
        div.removeChild(div.firstChild);
    }
     num = 0 ;
     serMap = new HashMap();
}

function delForLesson(){
    var str = '删除后无法复原，你确定全部删除吗?';
    swalToastr('操作提示', str, 'warning',doDelForLesson , '确定');
}

function doDelForLesson() {
    var div = document.getElementById("forMusDiv");
    while (div.hasChildNodes()){//当div下还存在子节点时 循环继续
        div.removeChild(div.firstChild);
    }
    forMap = new HashMap();
}

function delAllSick(){
    var str = '删除后无法复原，你确定全部删除吗?';
    swalToastr('操作提示', str, 'warning',doDelAllSick , '确定');
}

function doDelAllSick() {
    $(".note_lable[name=sicknessName]").each(function (index,value) {
        $(this).remove();
    });
}

function doCheckDataChange() {
    var data = getFromData('#contentForm');
    var detailContent = $.trim(ue.getContent());
    var detailLinkUrl = $("#detailLinkUrl").val();
    if(detailContent == '<p style="color:#c8ced4;">富文本 (包含课程大纲，课程说明，课程特点，适用人群）</p>'){
        detailContent = '';
    }
    if(contentDto.detailContent == '<p style="color:#c8ced4;">富文本 (包含课程大纲，课程说明，课程特点，适用人群）</p>'){
        contentDto.detailContent = '';
    }
    var freeTime = $("#freeTime").val();
    var topTime = $("#topTime").val();
    var idListStr = getlableNote('sicknessName', false).join(",");
    var titleListStr  = getlableNote('serTitle',false).join(",");
    var sample = data.sample;
    if($("#hiddenType").val() == 'lesson_series' || $("#hiddenType").val() == 'lesson_image'){
        sample = 'N';
    }
    var postData = {
        bizCode : data.bizCode,
        showType : data.showType,
        contentCode : data.contentCode,
        contentType : data.contentType,
        topTime : topTime,
        isvPid : data.isvPid,
        hasMidPage : data.hasMidPage,
        isTop : data.isTop,
        title : data.title,
        summary : data.summary,
        tips : data.tips,
        sample : sample,
        docCode : data.docCode,
        oneLevelDeptCode : data.oneLevelDeptCode,
        twoLevelDeptCode : data.twoLevelDeptCode,
        isFree : data.isFree,
        isPlatformCharge : data.isPlatformCharge,
        originPrice : data.originPrice,
        price : data.price,
        additionalRemarks : data.additionalRemarks,
        isHaveFreeTime : data.isHaveFreeTime,
        freeTime : freeTime,
        originReadedTotal : data.originReadedTotal,
        originLikedTotal : data.originLikedTotal,
        originBuyTotal : data.originBuyTotal,
        detailContent : detailContent,
        detailLinkUrl : detailLinkUrl,
    };
    var freeLessons = [];
    var forLessons = [];
    if($("#hiddenType").val() != 'lesson_series'){
        if($("#sample").val() == 'Y'){
            if(freeMap.size() >0){
            var freeArr = freeMap.keySet();
            for (var i = 0; i < freeArr.length; i++) {
                var freeLesson = {};
                var obj = JSON.parse(freeMap.get(freeArr[i]));
                if($("#hiddenType").val() != 'lesson_image'){
                    freeLesson.fileSize = obj.fileSize;
                    freeLesson.duration = obj.duration;
                }
                freeLesson.fileName = obj.fileName;
                freeLesson.lessonUrl = obj.lessonUrl;
                freeLessons.push(freeLesson);
            }
            }
        }
        if(forMap.size() > 0){
         var forArr = forMap.keySet();
        for (var i = 0; i < forArr.length; i++) {
            var forLesson = {};
            var obj = JSON.parse(forMap.get(forArr[i]));
            if($("#hiddenType").val() != 'lesson_image') {
                forLesson.fileSize = obj.fileSize;
                forLesson.duration = obj.duration;
            }
            forLesson.fileName = obj.fileName;
            forLesson.lessonUrl = obj.lessonUrl;
            forLesson.sortNum = $("#sortNum"+forArr[i]).val();
            forLessons.push(forLesson);
        }
        }
    }else{
        //说明是系列课程
        var lesson = [];
        if(serMap.length > 0){
         var forArr = serMap.keySet();
        for (var i = 0; i < forArr.length; i++) {
            var forLesson = {};
            var obj = JSON.parse(serMap.get(forArr[i]));
            forLesson.title = obj.fileName;
            forLesson.sortNum = $("#sortNum"+forArr[i]).val();
            forLesson.contentCode = obj.contentCode;
            lesson.push(forLesson);
        }
        }
    }
    if($("#hiddenType").val() != 'lesson_series'){
        if (!Compare(postData,contentDto) || CompareList(freeLessons,contentDto.freeLesson) || CompareList(forLessons,contentDto.formalLesson)
            || CompareStr(idListStr,contentDto.sickList) ||  CompareStr(titleListStr,contentDto.series)) {
            swalClosePageToastr(doBack);
            return;
        }
        doBack();
    }else{
        if (!Compare(postData,contentDto) || CompareList(lesson,contentDto.lesson)) {
            swalClosePageToastr(doBack);
            return;
        }
        doBack();
    }

}

function CompareStr(str,list){
    if(list == contentDto.sickList){
        var listStr = '';
        for (var i = 0; i <= list.length - 1; i++) {
            if (i < list.length - 1) {
                if (list[i] != '') {
                    listStr += list[i].refCode + ',';
                }
            } else {
                if (list[i] != '') {
                    listStr += list[i].refCode;
                }
            }
        }
        if (str != listStr) {
            return true;
        }
    }else if(list == contentDto.series){
        var listStr = '';
        for (var i = 0; i <= list.length - 1; i++) {
            if (i < list.length - 1) {
                if (list[i] != '') {
                    listStr += list[i].contentCode + ',';
                }
            } else {
                if (list[i] != '') {
                    listStr += list[i].contentCode;
                }
            }
        }
        if (str != listStr) {
            return true;
        }
    }
    return false;
}

function CompareList(list1,list2){
    if(list1.length != list2.length){
        return true;
    }
    if(list1.length > 0 && list2.length > 0){
    for(var i = 0; i < list1.length; i++){
        if(list2 == contentDto.freeLesson){
        if(list1[i].fileName != list2[i].fileName || list1[i].lessonUrl != list2[i].lessonUrl){
        if($("#hiddenType").val() != 'lesson_image') {
            if (list1[i].fileSize != list2[i].fileSize || list1[i].duration != list2[i].duration) {
                return true;
                }}
            return true;
        }
        return false;
        }else{
            if(list1[i].fileName != list2[i].fileName || list1[i].lessonUrl != list2[i].lessonUrl || list1[i].sortNum != list2[i].sortNum){
                if($("#hiddenType").val() != 'lesson_image') {
                    if (list1[i].fileSize != list2[i].fileSize || list1[i].duration != list2[i].duration) {
                        return true;
                    }}
            return true;
            }
            return false;
        }
    }
    }
    return false;
}

function doBack() {
    window.location.href = basePath + 'health/healthContentPage?title='+searchInfo.title+'&gmtCreateStr='+searchInfo.gmtCreateStr+'&dataStatus='+searchInfo.dataStatus+
        '&fcontentType='+searchInfo.fcontentType+'&oneLevelDeptCode='+searchInfo.oneLevelDeptCode+'&docCode='+searchInfo.docCode+'&docName='+searchInfo.docName+'&isvPid='+searchInfo.isvPid+'&isFree='+searchInfo.isFree
        +'&isPlatformCharge='+searchInfo.isPlatformCharge+'&isContentType='+searchInfo.isContentType+'&status='+searchInfo.status+'&isvName='+searchInfo.isvName
        +'&t='+ new Date().getTime()+ '&pageNo=' + searchInfo.pageNo + '&pageSize=' + searchInfo.pageSize;
}

function onClickTab(obj) {
    var id = $(obj).attr('id');
    if (id == '_tab1') {
        $('#_tab1').addClass('active');
        $('#_tab2').removeClass('active');
        $('#_tab3').removeClass('active');
        $('#_div2').css('display', 'none');
        $('#_div3').css('display', 'none');
        $('#_div1').css('display', 'block');
    } else if (id == '_tab2') {
        $('#_tab2').addClass('active');
        $('#_tab1').removeClass('active');
        $('#_tab3').removeClass('active');
        $('#_div1').css('display', 'none');
        $('#_div3').css('display', 'none');
        $('#_div2').css('display', 'block');
    } else {
        $('#_tab3').addClass('active');
        $('#_tab1').removeClass('active');
        $('#_tab2').removeClass('active');
        $('#_div1').css('display', 'none');
        $('#_div2').css('display', 'none');
        $('#_div3').css('display', 'block');
    }
}


//************************************************************************************************************************

//初始化编辑器
window.UEDITOR_CONFIG = {
    // 为编辑器实例添加一个路径，这个不能被注释
    UEDITOR_HOME_URL: basePath+"js/ueditor/",
    // 服务器统一请求接口路径
    serverUrl:basePath+ "ueditor/dispatch",
    placeholder:"Please enter some text..."
};
//初始化编辑器
var ue = UE.getEditor('detailContent', {
    initialFrameHeight:800,//编辑区域高度
    maximumWords:30000, autoHeightEnabled: false,
    autoFloatEnabled: true,allowDivTransToP: false,
    allowPreviewEmoticons : false,
    placeholder : 111,
    toolbars: [[
        'preview', //预览
        'source', //源代码
        'bold', //加粗
        'indent', //首行缩进
        'italic', //斜体meta
        'underline', //下划线
        'strikethrough', //删除线
        'subscript', //下标
        'fontborder', //字符边框
        'superscript', //上标
        'formatmatch', //格式刷
        'blockquote', //引用
        'pasteplain', //纯文本粘贴模式
        'horizontal', //分隔线
        'removeformat', //清除格式
        'time', //时间
        'date', //日期
        'link',
        'unlink', //取消链接
        'inserttitle', //插入标题
        // 'insertcode', //代码语言
        'fontfamily', //字体
        'fontsize', //字号
        // 'paragraph', //段落格式
        // 'emotion', //表情
        'spechars', //特殊字符
        'simpleupload', //单图上传
        'justifyleft', //居左对齐
        'justifyright', //居右对齐
        'justifycenter', //居中对齐
        'justifyjustify', //两端对齐
        'forecolor', //字体颜色
        'backcolor', //背景色
        // 'insertorderedlist', //有序列表
        // 'insertunorderedlist', //无序列表
        // 'directionalityltr', //从左向右输入
        // 'directionalityrtl', //从右向左输入
        'rowspacingtop', //段前距
        'rowspacingbottom', //段后距
        'imagenone', //默认
        'imageleft', //左浮动
        'imageright', //右浮动
        'imagecenter', //居中
        'lineheight', //行间距
        'edittip ', //编辑提示
        'customstyle', //自定义标题
        'autotypeset', //自动排版
        // 'help', //帮助
        'cleardoc' //清空文档
    ]]
});

uEditorPlaceholder(ue, '<p style="color:#c8ced4;">富文本 (包含课程大纲，课程说明，课程特点，适用人群）</p>');
// ue.placeholder('<p style="color:#c8ced4;">富文本 (包含课程大纲，课程说明，课程特点，适用人群）</p>');

$(function () {
    if (contentDto && (contentDto.detailLinkUrl != null || contentDto.detailLinkUrl != '')) {
        ue.ready(function() {
            ue.body.innerHTML = contentDto.detailContent ? contentDto.detailContent : '';
            //判断是否详情
            //ue.setDisabled('bold');
        });
    }
});

//********************************************************添加系列************************************************************
function selectSeries(){
    $("#serTitle").val("");
    doSeriesRefresh();
    $("#selectSeries").modal(true);
}

function doSeriesRefresh() {
    $('#dataSeriesTable').bootstrapTable('refresh', {
        url: basePath + 'health/getLessonDataForCheckbox?t='+new Date().getTime()
    });
}

$('#dataSeriesTable').on("click-row.bs.table", function (e, row, $element) {
    // checkBox 的勾选
    var index = $element[0].rowIndex - 1;
    $('#dataSeriesTable').bootstrapTable('uncheckAll');
    $('#dataSeriesTable').bootstrapTable('check', index);
});

function clickSeries() {
    var lessonList=[];
    var sicks=getSelectedRows('#dataSeriesTable');
    for (var cell in sicks){
        lessonList.push({value:sicks[cell].contentCode,text:sicks[cell].serTitle});
    }
    $('#selectSeries').modal('hide');
    addLableByList(lessonList,"serTitle");
}

function deleAllSeries(name){
    $(".note_lable[name=title]").each(function (index,value) {
        $(this).remove();
    });
}

function save(){
    var id = $("#hiddenId").val();
    if(id== null || id== ''){
        toastr.error("请先选择课程");
        return;
    }
    var idListStr  = getlableNote('title',false).join(",");
    var contentCode = $("#hiddenContent").val();
    var postData = {
        id :id,
        idListStr : idListStr,
        contentCode : contentCode
    }
    $.ajax({
        type: 'post',
        url: basePath + 'health/assSeriesLesson',
        dataType: 'json',
        data: postData,
        success : function (data) {
            if(data.result){
                window.location.href = basePath + 'health/healthContentPage?t=' + new Date().getTime();
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function checkPrice(value){
    if(Number(value) <= 0){
        toastr.error('现价必须大于0');
        $("#price").val('');
    }
}

function showQrCodes() {
    var detailLinkUrl = $.trim($("#detailLinkUrl").val());
    var detailContent = $.trim(ue.getContent());
    $("#qrcode").html("");
    if((detailLinkUrl == null || detailLinkUrl == '') && (detailContent == '' ||  detailContent == '<p style="color:#c8ced4;">富文本 (包含课程大纲，课程说明，课程特点，适用人群）</p>')){
        toastr.error('至少填写详情或富文本其中一个内容');
        return;
    }
    if(!(detailLinkUrl == null || detailLinkUrl == '')){
        initQrCode(detailLinkUrl);
        $("#scanQrCodePage1").modal('show');
        return;
    }
    var postData = {
        detailContent : detailContent,
    };
    $.ajax({
        type: 'post',
        url: basePath + 'health/getQrCode',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if(data.result){
                var content = data.content;
                initQrCode(content.detailContent);
                $("#scanQrCodePage1").modal('show');
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function initQrCode(url) {
    $('#qrcode').qrcode({
        height: 240,
        width: 240,
        text: url
    });
}


//*************************************OSS上传成功回调函数********************************************
function uploadFreeSuccess(result) {
    hideLoading();
    var ResUrl =  result.res.requestUrls[0];
    var url = ResUrl.substr(0,ResUrl.lastIndexOf("?"));
    var json = freeMap.get(freeNum);
    if($("#hiddenType").val() == 'lesson_image'){
        freeMap.put(freeNum,json+'"lessonUrl":"'+ ResUrl +'"}');
    }else{
        freeMap.put(freeNum,json +'","lessonUrl":"'+url+'"}');
    }
    $("#free").val('');
}


//上传正式文件成功回调
function uploadFormalSuccess(result) {
    hideLoading();
    var ResUrl =  result.res.requestUrls[0];
    var url = ResUrl.substr(0,ResUrl.lastIndexOf("?"));
    var json = forMap.get(countNum);
    if($("#hiddenType").val() == 'lesson_image'){
        forMap.put(countNum,json+'"lessonUrl":"'+ ResUrl +'"}');
    }else{
        forMap.put(countNum, json + '","lessonUrl":"' + url + '"}');
    }
    $("#formal").val('');
    countNum ++;
}

function uploadImgSuccess(result) {
    hideLoading();
    var ResUrl =  result.res.requestUrls[0];
    //var url = ResUrl.substr(0,ResUrl.lastIndexOf("."));
    resUrl =ResUrl;
}

function uploadFailed(){
    hideLoading();
}

function clearNoNum(obj){
    obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
    if(obj.value.indexOf(".")< 0 && obj.value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        obj.value= parseFloat(obj.value);
    }
}





